package dal;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.imageio.ImageIO;
import javax.swing.JOptionPane;

public class FileIO {
	private static String fileName = "map/my/";
	private static String ext = ".amg";
	
	
	/** save to file
	 * @param ms
	 * 	a map's structure
	 * @param thumb
	 * 	a map's thumb representation
	 * @return
	 *	true if save is successful
	 */
	public static boolean saveToFile(MapStruct ms, Thumb thumb) {
		int i = 0;
		File path = new File(fileName + i + ext);
		
		while(path.exists()){
			path = new File(fileName + ++i + ext);
		}
		
		try {
			ObjectOutputStream dout = new ObjectOutputStream(new FileOutputStream(path));
			dout.writeObject(thumb);
			dout.writeObject(new MapFileStruct(ms));
			dout.flush();
			dout.close();
		} catch(IOException e) {
			return false;
		}
		
		return true;
	}
	
	/**	read from file
	 * @param filename
	 * 	the path or name of the file
	 * @return
	 * 	the structure of a map or null if the file cannot be read
	 * @throws IOException
	 * 	if the file doesn't exists or the file content isn't readable 
	 */
	public static MapFileStruct loadFromFile(File fileName) {	
		try {
			ObjectInputStream din = new ObjectInputStream(new FileInputStream(fileName));
			din.readObject();	// thumb
			MapFileStruct map = (MapFileStruct) din.readObject();
			din.close();
			return map;
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "Sikertelen olvasas!\n" + e.getMessage(), "IOException", JOptionPane.ERROR_MESSAGE);
			return null;
		}
	}

	/**
	 * @param fileName
	 *	the path/name of the image
	 * @return
	 * 	null if there was an error, otherwise the image itself
	 */
	public static BufferedImage readPic(String fileName){
		try {
			return ImageIO.read(new File(fileName));
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "A kepet nem talalhato vagy nem lehet beolvasni\n" + e.getMessage(), "Hiba", JOptionPane.ERROR_MESSAGE);
		}
		
		return null;
	}
	
	/**
	 * @param fileName
	 * 	path for a map
	 * @return
	 * 	an thumb representation of a map
	 */
	public static Thumb readThumb(File fileName) {
		try {
			ObjectInputStream din = new ObjectInputStream(new FileInputStream(fileName));
			Thumb thumb = (Thumb) din.readObject();
			din.close();
			
			return thumb;
		} catch(Exception e) {
			JOptionPane.showMessageDialog(null, "Missing Fields\n" + e.getMessage(), "Deserialization", JOptionPane.ERROR_MESSAGE);
			return null;
		}
	}
}
